<script setup>
import Group from '@/components/Group/index.vue'
import aiApi from '@/api/ai/aiApi'
import { message } from 'ant-design-vue'
import WordEditor from '@/components/WordEditor/index.vue';
import * as monaco from "monaco-editor";

import aiChatApi from '@/api/ai/aiChatApi';

const aiConfig = ref({
	visiable: false,
	viewFlag: false,
	descriptionFlag: false,
	chatFlag: false
})

const activeKey = ref(1);

const wordEditor = ref();




const descriptionDiagClose = async () => {
	const c = wordEditor.value.getValue();
	aiConfig.value.description = JSON.stringify(c);
	await save();
	wordEditor.value.clear()
}


const tableRef = ref();

const search = ref();

const currentGroupId = ref(0);

const refresh = () => {
	tableRef.value.refresh();

}

onMounted(() => {

})

const jsonEditor = ref();

let monacoEditor = null;

const initMonacoEditor = () => {
	// 使用 - 创建 monacoEditor 对象
	if (monacoEditor) {
		return;
	}
	monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
		validate: false
	});
	monacoEditor = monaco.editor.create(jsonEditor.value, {
		theme: "vs-dark", // 主题
		value: "", // 默认显示的值
		language: "json",
		folding: true, // 是否折叠
		foldingHighlight: true, // 折叠等高线
		foldingStrategy: "indentation", // 折叠方式  auto | indentation
		showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
		disableLayerHinting: true, // 等宽优化
		emptySelectionClipboard: false, // 空选择剪切板
		selectionClipboard: false, // 选择剪切板
		automaticLayout: true, // 自动布局
		codeLens: false, // 代码镜头
		scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
		colorDecorators: true, // 颜色装饰器
		accessibilitySupport: "off", // 辅助功能支持  "auto" | "off" | "on"
		lineNumbers: "on", // 行号 取值： "on" | "off" | "relative" | "interval" | function
		lineNumbersMinChars: 5, // 行号最小字符   number
		enableSplitViewResizing: false,
		readOnly: false, //是否只读  取值 true | false
	});
	initJsonValue();

	// 监听值变化
	monacoEditor.onDidChangeModelContent((event) => {
		// const value = monacoEditor.getModel().getValue();
		setDataValue();
	});

}

const initJsonValue = () => {
	if (activeKey.value == 1) {
		monacoEditor.setValue(`{
  "header": {
    "app_id": "\${appId}",
    "uid": "\${uid}"
  },
  "parameter": {
    "chat": {
      "domain": "\${domain}",
      "temperature": 0.5,
      "max_tokens": 1024
    }
  },
  "payload": {
    "message": {
      "text": [

        /**:for(history in historys){**/
         {
          "role": "\${history.role}",
          "content":"\${history.content}"
         }\${historyLP.last ? "" : ","}

        /**:}**/
      ]
    }
  }
}`);
	} else if (activeKey.value == 2) {
		monacoEditor.setValue("");
	} else if (activeKey.value == 3) {
		monacoEditor.setValue("");
	} else if (activeKey.value == 4) {
		monacoEditor.setValue("");
	}

}

const columns = ref([
	{
		title: '编码',
		dataIndex: 'aiCode',
		key: 'aiCode',
		ellipsis: true,
	},
	{
		title: '名称',
		dataIndex: 'aiName',
		key: 'aiName',
		ellipsis: true,
	},
	{
		title: 'token',
		dataIndex: 'token',
		resizable: true,
		key: 'token',
		ellipsis: true,
	},
	{
		title: 'apiKey',
		dataIndex: 'apiKey',
		resizable: true,
		key: 'apiKey',
		ellipsis: true,
	},
	{
		title: 'apiSecret',
		dataIndex: 'apiSecret',
		key: 'apiSecret',
		ellipsis: true,
	},
	{
		title: 'domain',
		dataIndex: 'domain',
		key: 'domain',
		ellipsis: true
	},
	{
		title: '启停状态',
		dataIndex: 'disableFlag',
		key: 'disableFlag',
		mapping: [{
			key: '1',
			value: '停用'
		},
		{
			key: '0',
			value: '启用'
		}],
		fixed: 'right'

	}, {
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 410,
		fixed: 'right',
		buttonList: [
			{
				click: (field, record) => {
					aiConfig.value = record;
					aiConfig.value.descriptionFlag = true;

				},
				render: (record) => {
					return "描述";
				}
			},
			{
				type: "primary",
				click: (field, record) => {
					aiConfig.value = record;

					aiConfig.value.visiable = true;
				},
				render: (record) => {

					return "编辑";
				}
			},
			{
				click: (field, record) => {
					setStatusFlag(record);
				},
				render: (record) => {

					return record.disableFlag == 1 ? "启用" : "停用";
				}
			},

			{
				click: (field, record) => {
					remove(record)
				},
				render: (record) => {
					return "删除";
				}
			},

			{
				click: (field, record) => {
					aiConfig.value = record;
					aiConfig.value.chatFlag = true;
					nextTick(() => {
						initMonacoEditor();
						loadApiChatConfig();
					})
				},
				render: (record) => {
					return "chat";
				}
			},
		]
	},
])

const loadApiChatConfig = async () => {

	const data = await aiChatApi.getByAiId({
		aiId: aiConfig.value.id
	});

	if (!data) {
		return;
	}
	aiConfig.value.chatConfig = data;

	if (!data.templateConfig) {
		return
	}
	setEditorValue();
}



const remove = async (r) => {
	await aiApi.removeById({
		id: r.id
	})
	refresh();
}
const setStatusFlag = async (r) => {
	await aiApi.setStatusFlag({
		id: r.id,
		disableFlag: r.disableFlag == 1 ? 0 : 1
	})
	refresh();
}

const loadData = async () => {
	const data = await aiApi.list({
		groupId: currentGroupId.value == 0 ? null : currentGroupId.value
	});
	return data;
}

const selectTree = (id, code, name) => {
	currentGroupId.value = id;
	refresh();
}


const save = async () => {
	if (aiConfig.value.groupId) {
		currentGroupId.value = aiConfig.value.groupId
	}
	if (!currentGroupId.value) {
		message.info("请选择分组！");
		return
	}
	if (!aiConfig.value.aiCode) {
		message.info("请输入编码！");
		return
	}
	if (!aiConfig.value.aiName) {
		message.info("请输入名称！");
		return
	}
	aiConfig.value.groupId = currentGroupId.value;

	await aiApi.save(aiConfig.value)
	aiConfig.value = {}
	aiConfig.value.visiable = false;

	refresh();
}
const add = () => {
	aiConfig.value = {};
	aiConfig.value.visiable = true;
}

const saveAiChat = async () => {
	await aiChatApi.save({
		...aiConfig.value.chatConfig,
		aiId: aiConfig.value.id
	})

	aiConfig.value.chatFlag = false;
}

const setEditorValue = () => {

	if (activeKey.value == 1) {
		monacoEditor.setValue(aiConfig.value.chatConfig.templateConfig || '');
	} else if (activeKey.value == 2) {
		monacoEditor.setValue(aiConfig.value.chatConfig.urlTemplateConfig || '');
	} else if (activeKey.value == 3) {
		monacoEditor.setValue(aiConfig.value.chatConfig.headerTemplateConfig || '');
	} else if (activeKey.value == 4) {
		monacoEditor.setValue(aiConfig.value.chatConfig.responseTemplateConfig || '');
	}

}
const setDataValue = () => {
	let v = monacoEditor.getValue();
	if (activeKey.value == 1) {
		aiConfig.value.chatConfig.templateConfig = v;
	} else if (activeKey.value == 2) {
		aiConfig.value.chatConfig.urlTemplateConfig = v;
	} else if (activeKey.value == 3) {
		aiConfig.value.chatConfig.headerTemplateConfig = v;
	} else if (activeKey.value == 4) {
		aiConfig.value.chatConfig.responseTemplateConfig = v;
	}
}
</script>

<template>

	<a-row :gutter="10" class="mb-2">
		<a-col :span="5">
			<Group :selectTree="selectTree" relationTypeCode="AI"></Group>
		</a-col>
		<a-col :span="19">
			<a-row :gutter="10" class="mb-2">
				<a-col :span="24">
					<a-card>
						<a-space>
							<a-input-search placeholder="请输入内容" v-model:value="search"
								@search="refresh"></a-input-search>
							<a-button @click="add" type="primary">新增</a-button>
						</a-space>
					</a-card>
				</a-col>
			</a-row>

			<a-row :gutter="10" class="mb-2">
				<a-col :span="24">
					<a-card>
						<h-table :paged="false" ref="tableRef" :data="loadData" :columns="columns" height="420px">
						</h-table>
					</a-card>
				</a-col>
			</a-row>
		</a-col>
	</a-row>


	<drag-modal v-model:visible="aiConfig.visiable" width="400px" :okFlag="!aiConfig.viewFlag" @ok="save"
		@close="aiConfig.visiable = false" :closable="false">
		<a-form :model="aiConfig" ref="formRef" autocomplete="off">
			<a-form-item label="编码">
				<a-input v-model:value="aiConfig.aiCode" :disabled="aiConfig.id != null"></a-input>
			</a-form-item>
			<a-form-item label="名称">
				<a-input v-model:value="aiConfig.aiName"></a-input>
			</a-form-item>
			<a-form-item label="url">
				<a-input v-model:value="aiConfig.url"></a-input>
			</a-form-item>
			<a-form-item label="token">
				<a-input v-model:value="aiConfig.token"></a-input>
			</a-form-item>
			<a-form-item label="apiKey">
				<a-input v-model:value="aiConfig.apiKey"></a-input>
			</a-form-item>
			<a-form-item label="appId">
				<a-input v-model:value="aiConfig.appId"></a-input>
			</a-form-item>
			<a-form-item label="apiSecret">
				<a-input v-model:value="aiConfig.apiSecret"></a-input>
			</a-form-item>
			<a-form-item label="domain">
				<a-input v-model:value="aiConfig.domain"></a-input>
			</a-form-item>
		</a-form>
	</drag-modal>



	<a-modal v-model:open="aiConfig.descriptionFlag" :footer="null" :closable="false" width="100%" height="100%"
		wrap-class-name="full-modal" :afterClose="descriptionDiagClose">
		<WordEditor ref="wordEditor" :value="aiConfig.description" />
	</a-modal>


	<a-modal v-model:open="aiConfig.chatFlag" :closable="false" height="100%" @ok="saveAiChat">

		<a-tabs v-model:activeKey="activeKey" @change="setEditorValue">
			<a-tab-pane key="1" tab="发送内容配置">


			</a-tab-pane>
			<a-tab-pane key="2" tab="url配置" force-render>


			</a-tab-pane>
			<a-tab-pane key="3" tab="header配置">
			</a-tab-pane>
			<a-tab-pane key="4" tab="响应配置">
			</a-tab-pane>
		</a-tabs>

		<a-row class="mb-2">
			<a-col :span="24">
				<a-button type="primary" @click="initJsonValue">重置</a-button>
			</a-col>
		</a-row>
		<a-row>
			<a-col :span="24">
				<div id="jed" ref="jsonEditor" style="width: 100%; height: 600px;"></div>
			</a-col>
		</a-row>



	</a-modal>

</template>




<style scoped lang="less">
.full-modal {
	.ant-modal {
		max-width: 100%;
		top: 0;
		padding-bottom: 0;
		margin: 0;
	}

	.ant-modal-content {
		display: flex;
		flex-direction: column;
		height: calc(100vh);
	}

	.ant-modal-body {
		flex: 1;
	}
}

.my-modal {
	.ant-modal-footer {
		margin-bottom: 15px !important;
		z-index: 999 !important;
	}
}
</style>
